<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" :selfUpdate="true">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="工作室ID">
                <a-input placeholder="" v-model="queryParam.id" :allowClear="true" />
                <!--  @blur="(value)=>handleChangeQueryParam(value,'id')" -->
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="工作室名称">
                <a-input v-model="queryParam.name" placeholder="" :allowClear="true" />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="工作室等级">
                  <a-select v-model="queryParam.type" placeholder="请选择">
                    <a-select-option v-for="it in levelArr" :key="it.id" :value="it.id">{{ it.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="地区">
                  <a-cascader
                    v-model="queryParam.address"
                    :options="cityArr"
                    placeholder="地区"
                    :fieldNames="{ label: 'name', children: 'children', value: 'name' }"
                  />
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  @click="() => ((this.queryParam = {}), this.$refs.table.refresh(true))"
                  >重置</a-button
                >
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd"  v-action:studio_add>新建</a-button>
      </div>
      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
        :scroll="{ x: true }"
      >
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)" v-action:studio_update>编辑</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)" v-action:studio_update>删除</a>
            <a-divider type="vertical" />
            <a-popconfirm
              v-action:studio_update
              v-if="record.status == 2"
              :title="`是否${record.status == 2?'开启':'关闭'}?`"
              ok-text="是"
              cancel-text="否"
              @confirm="handleStatus(record, record.status == 2?1:2)"
            >
              <a>{{record.status == 2?'开启':'关闭'}}</a>
            </a-popconfirm>
            <!-- <a-popconfirm
              v-if="record.status == 1"
              title="是否关闭?"
              ok-text="是"
              cancel-text="否"
              @confirm="handleStatus(record, 2)"
            >
              <a>关闭</a>
            </a-popconfirm> -->
            
          </template>
        </span>
        <span slot="address" slot-scope="text, scope">
          <span>{{ `${scope.country}-${scope.province}-${scope.city}` }}</span>
        </span>
        <span slot="status" slot-scope="text">
          <a-tag :color="text | statusFilter(statusList, 'status')">{{
            text | statusFilter(statusList, 'name')
          }}</a-tag>
        </span>

        <span slot="adminList" slot-scope="text, scope">
          <div style="max-width: 200px">
            <span style="display: inline-block; margin-bottom: 5px" v-for="it in scope.adminList" :key="it.id">
              <a-tag color="blue">
                {{ it.userName }}
              </a-tag>
            </span>
          </div>
        </span>
        <span slot="taskNum" slot-scope="text, scope">
          <AWM-task :task="scope"></AWM-task>
          <!-- <span> {{ scope.taskNum || 0 }}/{{ scope.nowOverdueTaskNum || 0 }} / {{ scope.hisOverdueTaskNum || 0 }}/ {{ scope.underwayTaskNum || 0 }} </span> -->
        </span>
        <span slot="PLDetails" slot-scope="text, scope">
          <ul style="font-size:10px;">
            <li>总产出: {{ scope.outputPrice || 0 | NumberFormat }}</li>
            <li>总支出: {{ scope.expensePrice || 0 | NumberFormat }}</li>
            <li>保障金: {{ scope.guaranteePrice || 0 | NumberFormat }}</li>
          </ul>
        </span>
        
        <span slot="teamUser" slot-scope="text, scope">
          <span>{{ scope }}</span>
        </span>
        <span slot="typeList" slot-scope="text, scope">
          <a-tag color="orange" v-for="it in scope.typeList" :key="it.id">{{ it.typeName }}</a-tag>
        </span>
        <span slot="type" slot-scope="text">
         <a-tag :color="text | statusFilter(inOutTypeList, 'status')">{{
            text | statusFilter(inOutTypeList, 'name')
          }}</a-tag>
        </span>
        
        <span slot="projects" slot-scope="text, record">
          <div class="projects-wrap" v-if="text">
            {{ text ? text.length : '--' }}
            <a @click="handleProjects(record)">查看</a>
          </div>
          <span v-else>--</span>
        </span>
      </s-table>
      <studio-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :levelArr="levelArr"
        :projectTypeList="projectTypeList"
        :inOutTypeList="inOutTypeList"
        :country="country"
        :provinceArr="provinceArr"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <project-list :visible="projects.visible" :data="projects.data" @cancel="handleProjectsCancel"></project-list>
      <!-- <awm-editor style="height:400px"></awm-editor> -->
      <!-- <step-by-step-modal ref="modal" @ok="handleOk" /> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import cloneDeep from 'lodash.clonedeep'
import { STable, Ellipsis } from '@/components'
import { studioAdd, studioList, studioUpdate } from '@/api/system'
import { levelListByNoAuth, projectTypeListByNoAuth } from '@/api/noAuth'
// import StudioForm from './modules/StudioForm'
import StudioForm from './modules/A'
import { provinceArr } from '@/utils/ccity'
import { country } from '@/utils/country'
import { cityArr } from '@/utils/ccity'
import { Cascader } from 'ant-design-vue'
import ProjectList from './modules/projectList'
import AWMTask from '@/views/components/task'
// import AwmEditor from './modules/Editor'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    fixed: true,
  },
  {
    title: '名称',
    dataIndex: 'name',
    fixed: true,
  },
  {
    title: '地区',
    dataIndex: 'city',
    width: '180px',
    scopedSlots: { customRender: 'address' },
  },
  {
    title: '级别',
    dataIndex: 'levelName',
    sorter: true,
    key: 'levelName',
  },
  {
    title: '任务详情',
    dataIndex: 'taskNum',
    scopedSlots: { customRender: 'taskNum' },
  },
   {
    title: '盈亏情况',
    dataIndex: 'PLDetails',
    scopedSlots: { customRender: 'PLDetails' },
  },
  {
    title: '描述',
    dataIndex: 'remark',
    key: 'remark',
  },
  // {
  //   title: '管理员',
  //   dataIndex: 'adminList',
  //   scopedSlots: { customRender: 'adminList' },
  // },

  // {
  //   title: '项目(总/已完成/进行中/超时)',
  //   dataIndex: 'projectNum',
  //   sorter: true,
  //   key: 'projectNum',
  // },
  {
    title: '类型',
    dataIndex: 'typeList',
    key: 'typeList',
    scopedSlots: { customRender: 'typeList' },
  },
  {
    title: '是否内部',
    dataIndex: 'type',
    scopedSlots: { customRender: 'type' },
  },
  {
    title: '人数',
    dataIndex: 'teamUser',
    sorter: true,
    key: 'teamUser',
  },
  {
    title: '参与项目数',
    dataIndex: 'projects',
    scopedSlots: { customRender: 'projects' },
  },
  {
    title: '月收费',
    dataIndex: 'monthMoney',
    customRender: (text) => `￥ ${text || 0 }`,
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: '120px',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '添加人',
    dataIndex: 'addUserName',
    key: 'addUserName',
    customRender: (text) => text || '--',
  },
  {
    title: '添加时间',
    dataIndex: 'addTime',
    key: 'addTime',
    customRender: (text) => text || '--',
  },
  {
    title: '最后编辑人',
    dataIndex: 'lastUpdateUserName',
    key: 'lastUpdateUserName',
    customRender: (text) => text || '--',
  },
  {
    title: '最后编辑时间',
    dataIndex: 'lastUpdateTime',
    key: 'lastUpdateTime',
    customRender: (text) => text || '--',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' },
  },
]
const statusList = [
  {
    id: 1,
    name: '正常',
    status: '#91cc75',
  },
  {
    id: 2,
    name: '关闭',
    status: '#ee6666',
  },
]
const inOutTypeList = [
   {
    id: 1,
    name: '是',
    status: '#91cc75',
  },
  {
    id: 2,
    name: '否',
    status: '#ee6666',
  },
]

let countryArr = country.map((v) => {
  return {
    name: v.chinese_name,
  }
})

export default {
  name: 'AMW-userList',
  components: {
    STable,
    Ellipsis,
    StudioForm,
    ProjectList,
    AWMTask,
    // AwmEditor,
    'a-cascader': Cascader,
  },
  data() {
    this.columns = columns
    return {
      statusList,
      inOutTypeList,
      cityArr,
      provinceArr: provinceArr,
      country: countryArr,
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      parameter: {
        pageNum: 1,
        pageSize: 10,
      },
      levelArr: [],
      projectTypeList: [],
      queryParam: {
        country: '中国',
      },
      data: [],
      sortJ: {
        levelName: 'level_num',
        teamUser: 'team_user',
        projectNum: 'project_num',
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let sortJ = this.sortJ
        if (parameter.sortField) {
          parameter.sortJ = sortJ
        }
        let queryParam = cloneDeep(this.queryParam)
        let { address } = queryParam
        if (address) {
          queryParam.country = address[0]
          queryParam.province = address[1]
          queryParam.city = address[2]
          delete queryParam.address
        }
        const requestParameters = Object.assign({}, parameter, queryParam)
        return studioList(requestParameters).then((res) => {
          let result = {
            data: res.data.data.map((v) => {
              let task = {}
              if (v.taskInfo) {
                let a = JSON.parse(v.taskInfo)
                task = {
                  nowOverdueTaskNum: a.finishNumByAssets || 0 + a.finishNumByShot || 0,
                  underwayTaskNum: a.hisDelayNumByAssets || 0 + a.hisDelayNumByShot || 0,
                  hisOverdueTaskNum: a.nowDelayNumByAssets || 0 + a.nowDelayNumByShot || 0,
                  taskNum: a.totalNumByAssets || 0 + a.totalNumByShot || 0,
                }
              }
              return {
                ...task,
                ...v,
              }
            }),
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalCount: res.data.total,
            totalPage: res.data.pages,
          }
          return result
        })
      },
      projects: {
        data: [],
        visible: false,
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },

  created() {
    // let query = this.$route.query
    // this.queryParam = {...this.queryParam, ...query}
    this.getLevel()
    this.getProjectTypeList()
    // getRoleList({ t: new Date() })
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      }
    },
    c_cityArr: function () {
      let provinceArr = cloneDeep(this.provinceArr)
      let queryParam = cloneDeep(this.queryParam)
      if (queryParam.province) {
        let i = provinceArr.findIndex((v) => v.name == queryParam.province)
        return provinceArr[i].cityList
      } else {
        return []
      }
    },
  },
  methods: {
    handleChangeQueryParam(e, key) {
      this.queryParam[key] = e.target.value
    },
    getLevel() {
      levelListByNoAuth({ pageNum: 1, pageSize: 10, type: 2 }).then((res) => {
        this.levelArr = res.data.data
      })
    },
    getProjectTypeList() {
      projectTypeListByNoAuth({ pageNum: 1, pageSize: 10 }).then((res) => {
        this.projectTypeList = res.data.data
      })
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    saveCB() {
      const form = this.$refs.createModal.form
      this.visible = false
      this.confirmLoading = false
      // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          values.typeList = [{ typeId: values.typeList }]
          // if(values.typeList){
          //   values.typeList = values.typeList.map(v=>{return {"typeId":v}})
          // }
          if (values.address) {
            values.country = values.address[0]
            values.province = values.address[1]
            values.city = values.address[2]
            delete values.address
          }

          if (values.id > 0) {
            if (values.adminList) {
              values.adminList = values.adminList.map((v) => {
                return { userId: v }
              })
            }
            studioUpdate(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('修改成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          } else {
            delete values.id
            studioAdd(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('新增成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleDel(a_record) {
      let self = this
      const modal = this.$confirm({
        title: '工作室删除',
        content: `是否删除工作室:${a_record.name}`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => self.handleDelete(a_record.id, modal),
        onCancel: () => {},
      })
    },
    handleDelete(a_id, a_modal) {
      return new Promise((resolve, reject) => {
        let data = { id: a_id, status: -1 }
        studioUpdate(data)
          .then((res) => {
            this.$refs.table.refresh()
            this.$message.success('删除成功!')
            resolve()
          })
          .catch((err) => {
            a_modal.destroy()
            this.$message.error('操作失败!')
          })
      })
    },
    handleProjects(a_record) {
      this.projects.data = a_record.projects
      this.projects.visible = true
    },
    handleProjectsCancel() {
      this.projects.data = {}
      this.projects.visible = false
    },
    handleStatus(a_record,a_type){
      studioUpdate({ id: a_record.id, status: a_type})
      .then(res=>{
        this.$message.success('操作成功!')
        this.$refs.table.refresh()
      }).finally(()=>{

      })
    }
  },
}
</script>
<style scoped lang="less">
.projects-wrap {
  position: relative;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 60px;
  a {
    position: absolute;
    right: 0;
  }
}
</style>

 